package com.masterclient.app.businessmodule.minemodule.address.contract;

import com.eoner.baselib.enums.FCPageViewState;
import com.eoner.baselib.presenter.ThrowableConsumer;
import com.eoner.baselib.utils.toast.ToastUtil;
import com.masterclient.app.httpservice.RetrofitUtil;
import com.eoner.baselibrary.bean.address.AddressBean;
import com.eoner.baselibrary.bean.address.DefaultAddressBean;

import java.util.List;

import io.reactivex.Observable;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
* Created by TMVPHelper on 2017/07/28
*/
public class ChangeAddressPresenter extends ChangeAddressContract.Presenter{

    public List<AddressBean.DataBean.ShItemsBean> list;

    @Override
    public void getAddressList() {

        if (list == null || list.size() == 0) {
            mView.baseShowPageLoading(false);
        }
        Observable<AddressBean> observable = RetrofitUtil.getInstance().getAddressList();
        Disposable disposable = toSubscribe(observable, new Consumer<AddressBean>() {
            @Override
            public void accept(@NonNull AddressBean bean) throws Exception {
                mView.baseRefreshPageState(FCPageViewState.PAGE_STATE_NORMAL);
                mView.baseHiddenPageLoading();
                if(bean!=null && bean.getData()!=null){
                    mView.getAddressSuccess(bean.getData());
                } else {
                    mView.baseShowError();
                    ToastUtil.showToast(SERVER_FAILED_STR);
                    if (list == null || list.size() == 0) {
                        mView.baseRefreshPageState(FCPageViewState.PAGE_STATE_NET_ERROR);
                    }
                }
            }
        },  new ThrowableConsumer(){
            @Override
            public void accept(Throwable o) throws Exception {
                super.accept(o);
                mView.baseHiddenPageLoading();
                mView.baseShowError();
                ToastUtil.showToast(WEB_FAILED_STR);
                if (list == null || list.size() == 0) {
                    mView.baseRefreshPageState(FCPageViewState.PAGE_STATE_NET_ERROR);
                }
            }
        });
        mRxManager.add(disposable);
    }

    @Override
    public void setAddressDefault(String id) {
        Observable<DefaultAddressBean> observable = RetrofitUtil.getInstance().setAddressDefault(id);
        Disposable disposable = toSubscribe(observable, new Consumer<DefaultAddressBean>() {
            @Override
            public void accept(@NonNull DefaultAddressBean bean) throws Exception {
                if("0".equals(bean.getCode())){
                    mView.changeDefaultSuccess();
                }else {
                    mView.changeDefaultfailed();
                }
            }
        }, new ThrowableConsumer());
        mRxManager.add(disposable);
    }

}